ENT.Type 			= "point"
ENT.Base 			= "base_point"
ENT.PrintName		= ""
ENT.Author			= ""

function ENT:Initialize()
	// Get keyvalues and use them
	
	self.Entity:SetName(self.Entity["targetname"])
	
	tempangles = string.Explode(" ",self.Entity["angles"]) or {0, 0, 0}
	self.Entity:SetAngles(Angle(tempangles[1],tempangles[2],tempangles[3]))
	
	self.Radius=tonumber(self.Entity["radius"]) or 32
	self.Frequency=tonumber(self.Entity["frequency"]) or 15
	self.MaxActive=tonumber(self.Entity["maxactive"]) or 10
	self.NextSpawn = CurTime() + self.Frequency
	self.NextCorrection = CurTime()

	self.Relationshipper=ents.Create("ai_relationship")
		self.Relationshipper:SetPos(self:GetPos())
		self.Relationshipper:SetKeyValue("spawnflags","1")
		self.Relationshipper:SetKeyValue("subject","npc_zombie")
		self.Relationshipper:SetKeyValue("target","player")
		self.Relationshipper:SetKeyValue("disposition","1")
		self.Relationshipper:SetKeyValue("radius",tostring(self.Radius))
		self.Relationshipper:SetKeyValue("rank","100")
		self.Relationshipper:SetKeyValue("StartActive","1")
		
	self.Relationshipper2=ents.Create("ai_relationship")
		self.Relationshipper2:SetPos(self:GetPos())
		self.Relationshipper2:SetKeyValue("spawnflags","1")
		self.Relationshipper2:SetKeyValue("subject","npc_zombie")
		self.Relationshipper2:SetKeyValue("target","npc_citizen")
		self.Relationshipper2:SetKeyValue("disposition","1")
		self.Relationshipper2:SetKeyValue("radius",tostring(self.Radius))
		self.Relationshipper2:SetKeyValue("rank","95")
		self.Relationshipper2:SetKeyValue("StartActive","1")
	
	self.ZedList={}	
end 

function ENT:KeyValue(key, value)
	if (self.Entity:IsOutput(key)) then self.Entity:StoreOutput(key,value)
	else self.Entity[key]=value end
end

function ENT:Think()
	if CurTime() > self.NextSpawn then
		self:SpawnZombie()
		self.NextSpawn = CurTime() + self.Frequency
	end
	/*if CurTime() > self.NextCorrection then
		for k, v in pairs( self.ZedList ) do
			if ( v:IsValid() ) then
				v:Fire("ForgetEntity","player",0)
				v:SetEnemy(player.GetByID(1))
				v:SetLastPosition(player.GetByID(1):GetPos())
				v:Fire("UpdateEnemyMemory","player",0)
			end
		end
		self.NextCorrection = CurTime() + 1
	end*/
end

function ENT:SpawnZombie()
	if self:CanSpawnZombie() and true /* delete that bit when it's time to make it work */ then
		local model = RandomZombieModel()
		local entity = ents.Create( "npc_zombie" )
			entity:SetPos( self:GetPos() + Vector( 0, 0, 0 ))
			entity:SetAngles( self:GetAngles() )
			entity:SetKeyValue( "squadname", "SQUAD_ZOMBIES" )
			entity:SetKeyValue( "spawnflags", "1796" )
			entity:SetKeyValue( "worldmodel", model )
			entity:SetKeyValue( "model", model )
			entity:SetName( model )
			//entity:SetKeyValue( "spawnflags", "772" )
			//entity:SetEnemy(player.GetByID(1))
			entity:Spawn()
			
			
			// Holy shit, zombies that can use doors. We're fucked!
			entity:CapabilitiesAdd( CAP_MOVE_GROUND | CAP_USE | CAP_AUTO_DOORS | CAP_OPEN_DOORS | CAP_INNATE_MELEE_ATTACK1 )
			
			// TODO: Make zombies hate generators by using npc_bullseyes
			
			entity:SetModel(model)
		
		// This bit makes the zombies hate the players, thereby making them move their lazy asses
		self.Relationshipper:Fire("ApplyRelationship", true, 0.1)
		self.Relationshipper2:Fire("ApplyRelationship", true, 0.1)
		
		// Add this new zombie to the list
		table.insert( self.ZedList, entity )
	end
end 

function ENT:CanSpawnZombie()
	me=self.Entity
	
	for k, v in pairs( self.ZedList ) do
		if ( !v:IsValid() ) then
			table.remove( self.ZedList, k )
			//print( "Removing dead zed..." )
		end
	end
	
	if (#self.ZedList>=self.MaxActive) then
		//print( "Too many active zombies, won't spawn!" )
		return false
	end
	
	// TODO: Fix this shit!
	/*for _, ply in pairs( player.GetAll() ) do
		for _, ent in pairs( FindInView( ply ) ) do
			if ent == self then
				local trace = {}
				
				trace.start		= ply:GetPos()
				trace.endpos   	= ent:GetPos()
				trace.Filter	= self
				
				traceres = util.TraceLine( trace )
				
				if traceres.HitWorld then
					Msg( "Trace hit world, can spawn!\n" )
				else
					Msg( "Entity in a players FOV, cannot spawn!\n" )
					return false
				end
			end
		end
	end*/
	//print( "TODO: Check to see if any player can see this entity!" )
	
	for k, v in pairs( ents.FindInSphere( self:GetPos(), self.Radius ) ) do
		if v:IsPlayer() then
			//print( "Player Too close, cannot spawn!" )
			return false
		end		
	end
	
	for k, v in pairs( ents.FindInSphere( self:GetPos(), 2 ) ) do
		if v:GetClass()=="npc_zombie" then
			//print( "Zombie on top of spawn, cannot spawn!" )
			return false
		end		
	end
	
	//print( "Can Spawn!" )
	return true
end 

function FindInView( thisplayer )
	local thisangle = thisplayer:GetAimVector():Angle()

	local thisyawmin = Angle(0,0,0)
	thisyawmin.Yaw = thisangle.Yaw - (thisplayer:GetFOV()/2)
	thisyawmin.Pitch = thisangle.Pitch
	thisyawmin.Roll = thisangle.Roll
	
	local thisyawmax = Angle(0,0,0)
	thisyawmax.Yaw = thisangle.Yaw + (thisplayer:GetFOV()/2)
	thisyawmax.Pitch = thisangle.Pitch
	thisyawmax.Roll = thisangle.Roll
	
	local ent_list = {}
	ent_list = ents.FindByClass("*")
	
	local results = {}

	local p1 = thisplayer:GetPos()
	for _, ent in pairs(ent_list) do

		if (thisplayer != ent) then
			local p2 = ent:GetPos()
			local pDir = p2 - p1
			local ang = pDir:Angle()

			local CS = (ang.Yaw >= thisyawmin.Yaw and ang.Yaw <= thisyawmax.Yaw)

			if (CS) then
				table.insert(results, ent)
			end
		end
	end
	return results
end 

function ENT:IsOutput(o)
	return false
end
